package com.xhsj.user.pms.patent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xhsj.user.generalprocess.entity.TbPamGeneralOpinionFile;
import com.xhsj.user.generalprocess.entity.TbPamGeneralProcessHiTask;
import com.xhsj.user.generalprocess.entity.TbPamGeneralProcessTask;
import com.xhsj.user.generalprocess.mapper.TbPamGeneralOpinionFileMapper;
import com.xhsj.user.generalprocess.mapper.TbPamGeneralProcessHiTaskMapper;
import com.xhsj.user.generalprocess.mapper.TbPamGeneralProcessTaskMapper;
import com.xhsj.user.generalprocess.service.TbPamGeneralProcessHiTaskService;
import com.xhsj.user.generalprocess.service.TbPamGeneralProcessTaskService;
import com.xhsj.user.hr.process.dto.pam.TbPamGeneralOpinionFileDto;
import com.xhsj.user.hr.process.dto.pam.TbPamOverseasApplyCountryDto;
import com.xhsj.user.hr.process.dto.pam.TransferPCTOrPRCDataDto;
import com.xhsj.user.hr.system.mapper.TbGlobalUserMapper;
import com.xhsj.user.pms.overseas.entity.TbPamOverseasPrompt;
import com.xhsj.user.pms.overseas.query.ApplyNumAndPublicNumQuery;
import com.xhsj.user.pms.overseas.service.TbPamOverseasPromptService;
import com.xhsj.user.pms.patent.domain.*;
import com.xhsj.user.pms.patent.dto.PatentByArchivesNumDto;
import com.xhsj.user.pms.patent.dto.PatentByModelTypeDto;
import com.xhsj.user.pms.patent.mapper.*;
import com.xhsj.user.pms.patent.query.InventorListQuery;
import com.xhsj.user.pms.patent.query.OperationerListQuery;
import com.xhsj.user.pms.patent.query.TransferPCTOrPRCDataQuery;
import com.xhsj.user.pms.patent.service.DisclosureService;
import com.xhsj.user.pms.patent.service.TbPamInventorProposalIprService;
import com.xhsj.user.pms.patent.service.TbPamOverseasApplyService;
import com.xhsj.user.pms.workflow.dto.ExecProgressDto;
import com.xhsj.user.pms.workflow.mapper.WorkflowNodeMapper;
import com.xhsj.user.pms.workflow.service.impl.WorkflowExecServiceImpl;
import com.xhsj.user.utils.IdGen;
import com.xhsj.user.utils.Message;
import com.xhsj.user.utils.StringUtils;
import com.xhsj.user.utils.UserUtils;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Description:
 * @Auther: 罗季嘉
 * @Date: 2020/1/16 15:42
 */
@Slf4j
@Service
@Transactional
public class DisclosureServiceImpl implements DisclosureService {

    @Autowired
    private DisclosureMapper disclosureMapper;
    @Autowired
    private DisclosureInventorMapper disclosureInventorMapper;

    @Autowired
    private PatentFileMapper patentFileMapper;

    @Autowired
    private OpinionMapper opinionMapper;

    @Autowired
    private TbGlobalUserMapper userMapper;

    @Autowired
    private WorkflowNodeMapper workflowNodeMapper;

    @Autowired
    private JudgesUserMapper judgesUserMapper;

    @Autowired
    private JudgesMapper judgesMapper;

    @Autowired
    private TbPamJudgesReviewRecordMapper judgesReviewRecordMapper;

    @Autowired
    private TbPamJudgesReviewRecordFileMapper tbPamJudgesReviewRecordFileMapper;

    @Autowired
    private TbPamInventorProposalIprService tbPamInventorProposalIprService;

    @Autowired
    private PatentServiceImpl patentServiceImpl;

    @Autowired
    private TbPamInventorProposalIprMapper tbPamInventorProposalIprMapper;

    @Autowired
    private TbPamOverseasApplyMapper tbPamOverseasApplyMapper;

    //助理
    @Value("${rolekeyname.assistantName}")
    private String assistantName;

    @Autowired
    private WorkflowExecServiceImpl workflowExecServiceImpl;

    @Autowired
    private TbPamOverseasApplyService tbPamOverseasApplyService;

    @Autowired
    private TbPamOverseasApplyCountryMapper tbPamOverseasApplyCountryMapper;

    @Autowired
    private TbPamGeneralProcessTaskMapper tbPamGeneralProcessTaskMapper;

    @Autowired
    private TbPamGeneralProcessHiTaskMapper tbPamGeneralProcessHiTaskMapper;

    @Autowired
    private TbPamOverseasApplyMapper dao;

    @Autowired
    private TbPamOverseasPromptService tbPamOverseasPromptService;

    @Autowired
    private TbPamGeneralOpinionFileMapper tbPamGeneralOpinionFileMapper;

    @Autowired
    private TbPamGeneralProcessHiTaskService tbPamGeneralProcessHiTaskService;

    @Autowired
    private TbPamGeneralProcessTaskService tbPamGeneralProcessTaskService;

    @Autowired
    private TbPamOverseasApplyFileMapper tbPamOverseasApplyFileMapper;


    /**
     * 创建交底书
     *
     * @param disclosure
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createDisclosureAndFile(Disclosure disclosure, Long users, String label, int jumpForm, String roleKeyname, String deptName) throws Exception{
        try {
            if (disclosure != null) {
                StringBuilder stringBuilder = new StringBuilder();
                List<DisclosureInventor> inventorList = disclosure.getInventorList();
                for (DisclosureInventor disclosureInventor : inventorList) {
                    disclosureInventor.setId(IdGen.generateUUID());
                    disclosureInventor.setCreateBy(disclosure.getCreatedUser().toString());
                    disclosureInventor.setCreateDate(new Date());
                    disclosureInventor.setUpdateDate(new Date());
                    disclosureInventor.setDisclosureId(disclosure.getDisclosureId());
                    disclosureInventor.setDelFlag(0);
                    stringBuilder.append(";"+disclosureInventor.getInventor()+":"+disclosureInventor.getWeight()+"%");
                    disclosureInventorMapper.insert(disclosureInventor);
                }
                String substring = stringBuilder.toString().substring(1);
                //创建交底书及文件
                disclosure.setInventor(substring);
                disclosure.setCreatedTime(new Date());
                disclosure.setUpdateTime(new Date());
                int i = disclosureMapper.insert(disclosure);
                if(i != 1){
                    throw new Exception("创建交底书异常请联系管理员");
                }
                List<PatentFile> patentFileList = disclosure.getPatentFileList();
                for (PatentFile patentFile : patentFileList) {
                    patentFile.setDiscId(disclosure.getDisclosureId());// 交底书id
                    patentFile.setOwnerAs(String.valueOf(disclosure.getCreatedUser()));
                    patentFile.setCheckType(0);
                    patentFile.setPatentFileId(IdGen.generateUUID());
                    int i1 = patentFileMapper.insert(patentFile);
                    if(i1 != 1){
                        throw new Exception("创建交底书异常请联系管理员");
                    }
                }
                   //保存发明人建议ipr
                List<Long> inventorProposalIprs = disclosure.getInventorProposalIprs();
                if(inventorProposalIprs.size()>0) {
                    for (Long inventorProposalIpr : inventorProposalIprs) {
                        TbPamInventorProposalIpr tbPamInventorProposalIpr = new TbPamInventorProposalIpr();
                        tbPamInventorProposalIpr.setDisclosureId(disclosure.getDisclosureId());
                        tbPamInventorProposalIpr.setUserId(String.valueOf(inventorProposalIpr));
                        tbPamInventorProposalIpr.setCreateBy(String.valueOf(disclosure.getCreatedUser()));
                        tbPamInventorProposalIpr.setUpdateBy(String.valueOf(disclosure.getCreatedUser()));
                        if (!tbPamInventorProposalIprService.save(tbPamInventorProposalIpr)) {
                            throw new Exception("保存发明人建议ipr失败");
                        }
                    }
                }

                //启动流程
                ExecProgressDto param=new ExecProgressDto();
                param.setNodeId("003BFA10D8934DF992E34DED81787CCC");
                param.setDisclosureId(disclosure.getDisclosureId());
                param.setUsers(Arrays.asList(users));
                param.setLabel(label);
                param.setJumpForm(jumpForm);
                param.setNodeName("交底书(创建)");
                param.setCreateTime(new Date());
                param.setFlowCode(0);
                param.setStartFlow(true);
                workflowExecServiceImpl.execProgress2(param);

//                HashMap<String, Object> map = new HashMap<>();
//                map.put("zhuguan", users);
//                // 启动流程
//                flowableService.startProcess(disclosure.getDisclosureId(),map,"patent_apply",(entity) -> {
//                    Disclosure disclosure1 = new Disclosure();
//                    disclosure1.setDisclosureId(disclosure.getDisclosureId());
//                    disclosure1.setProcessInstanceId(entity.getProcessInstanceId());
//                    disclosureMapper.updateById(disclosure1);
//                });
//                Disclosure disclosure1 = new Disclosure();
//                disclosure1.setNodeId();
//                disclosure1.setNodeName()
//                disclosureMapper.updateById(disclosure1);
                //

            }else {
                throw new Exception("创建交底书异常请联系管理员");
            }
        }catch (Exception e){
            log.error("创建交底书异常",e);
            throw e;
        }

    }

    /**
     * 获取我的交底书列表
     * @param userId
     * @return
     */
    @Override
    public IPage<Disclosure> selectMyPatentList(IPage page,Long userId, Map<String, Object> param,String roleKeyname) {
        String name = Objects.isNull(param.get("name"))?"":String.valueOf(param.get("name"));
        String inventor = Objects.isNull(param.get("inventor"))?"":String.valueOf(param.get("inventor"));
        String fullName = Objects.isNull(param.get("createdUser"))?"":String.valueOf(param.get("createdUser"));
        String deptName = Objects.isNull(param.get("dept_name"))?"":String.valueOf(param.get("dept_name"));
        String archivesNum = Objects.isNull(param.get("archivesNum"))?"":String.valueOf(param.get("archivesNum"));
        // 流程专员得用户id
        boolean isProcessSpecialist = false;
        boolean frozenButton = false;
        List<Long> userIdList = userMapper.getUserIdByRoleName(roleKeyname);
        if (userIdList.contains(userId)) {
            isProcessSpecialist = true;
            frozenButton = true;
        }
        userIdList.add(userId);
        IPage<Disclosure> disclosureIPage = disclosureMapper.selectMyPatentList(page, userId, name, inventor, fullName, deptName, archivesNum, isProcessSpecialist, frozenButton);
        // 技术领域
        List<Disclosure> records = disclosureIPage.getRecords();
        List<String> collect = records.stream().map(Disclosure::getDisclosureId).collect(Collectors.toList());
        if(collect != null && collect.size() != 0 ) {
            Map<String,Map<String,String>> judgesById = judgesMapper.getJudgesById(collect);
            records.forEach(record -> {
                    if (judgesById.containsKey(record.getDisclosureId())) {
                        record.setJudgesName(judgesById.get(record.getDisclosureId()).get("judgesName"));
                    }
            });
        }
        // 得到操作人
        this.getOperationer(records);
        return disclosureIPage;
    }

    public void getOperationer(List<? extends Disclosure> records){
        // 获取对应交底书id数组
        List<String> disclosureIdList = records.stream().map(item -> item.getDisclosureId()).collect(Collectors.toList());
        if(StringUtils.isNotBlank(disclosureIdList) && disclosureIdList.size() !=0 ) {
            // 发明人
            Map<String, InventorListQuery> inventorList = disclosureInventorMapper.getInventorList(disclosureIdList);
            // 获取操作人通过底书id
            Map<String, OperationerListQuery> adviceIprList = tbPamInventorProposalIprMapper.getAdviceIprList(disclosureIdList);
            records.forEach(item -> {
                if (adviceIprList.containsKey(item.getDisclosureId()) && !"003BFA10D8934DF992E34DED81787CCC".equals(item.getNodeId()) && !"19181F68A04841F2AE079A8D52925200".equals(item.getNodeId()))
                    item.setConveyancer(adviceIprList.get(item.getDisclosureId()).getFullName());
                if (inventorList.containsKey(item.getDisclosureId())){
                    item.setInventor(inventorList.get(item.getDisclosureId()).getInventor());
                }
            });
        }
    }

    /**
     * 查询交底书编号是否存在
     * @param num
     * @return
     */
    @Override
    public Integer getNumCount(String num) {
        return disclosureMapper.getNumCount(num);
    }

    /**
     * 查询最新编号并+1
     * @return
     */
    @Override
    public String getNewNum() {
        String num = disclosureMapper.getNewNum();
        Calendar cal = Calendar.getInstance();
        String year = cal.get(Calendar.YEAR)+"";
        int i = 1;
        if (StringUtils.isNotBlank(num)){
            String s = num.substring(3, num.length());
            i = Integer.parseInt(s)+1;
        }
        String s1 = StringUtils.addZeroForNum(String.valueOf(i), 4);
        String yearStr = year.substring(2, 4);
        return "D"+yearStr+s1;
    }

    /**
     * 通过主键ID查询交底书以及文件
     * @param disclosureId
     * @return
     */
    @Override
    public Disclosure getDisclosureByDisclosureId(String disclosureId, Integer fileType) {
        Disclosure disclosure = disclosureMapper.getDisclosureByDisclosureId(disclosureId);
        if (disclosure !=null) {
            List<PatentFile> list = patentFileMapper.getLatestFileByFileType(disclosureId,fileType);
            disclosure.setPatentFileList(list);
            //建议IPR
            List<Long> strings = tbPamInventorProposalIprMapper.getAdviceIpr(disclosureId);
            disclosure.setInventorProposalIprs(strings);
            // 技术领域
            List<String> collect  = Arrays.asList(disclosureId);
            if(collect != null && collect.size() != 0) {
                Map<String,Map<String,String>> judgesById = judgesMapper.getJudgesById(collect);
                    if (judgesById.containsKey(disclosure.getDisclosureId())) {
                        disclosure.setJudgesName(judgesById.get(disclosure.getDisclosureId()).get("judgesName"));
                    }

            }
            // 判断当前用户是什么技术负责人 说明人
//            Long userId = UserUtils.getLoginAppUser().getUserId();
//            List<Long> list_f = disclosureMapper.getPatentUserIdByDisclosureId(disclosureId);
//            if (list_f.contains(userId))
//                disclosure.setFeedbackButton(true);

        }
        return disclosure;
    }


    /**
     * 通过主键ID查询交底书以及文件-评审会初审
     * @param disclosureId
     * @return
     */
    @Override
    public Disclosure firstReviewTrial(String disclosureId, List<Integer> fileType, List<Integer> checkTypeList) {
        Disclosure disclosure = disclosureMapper.getDisclosureByDisclosureId(disclosureId);
        if (disclosure !=null) {
            // 通过交底书id查询最新专利文件
            List<PatentFile> list = patentFileMapper.getAllPatentFileByOwnerAs(disclosureId,fileType,checkTypeList);
            disclosure.setPatentFileList(list);
        }
        return disclosure;
    }

    @Override
    public List<IprWorkLoad> getIprWorkload() {
        return disclosureMapper.getIprWorkload();
    }

    // 冻结专利和解冻专利
    @Override
    public void disclosureFrozenStatus(int frozenStatus, String disclosureId,String frozenRemarks) throws Exception {
        // 修改冻结状态
        Disclosure disclosure = new Disclosure();
        disclosure.setDisclosureId(disclosureId);
        disclosure.setFrozenStatus(frozenStatus);
        disclosure.setFrozenRemarks(frozenRemarks);
        if (disclosureMapper.updateById(disclosure) != 1) {
            throw new Exception("修改冻结状态异常");
        }

    }

    @Override
    public Map<String, List<OpinionsAndFile>> getOpinions(String disclosureId) {
        Map<String, List<OpinionsAndFile>> map = Maps.newLinkedHashMap();
        map.put("zgOpinion",Lists.newArrayList());//主管意见
        map.put("cxOpinion",Lists.newArrayList());//查新意见
        map.put("cjrToIprOpinion",Lists.newArrayList());//创建人回复ipr意见
        map.put("cjrXzOpinion",Lists.newArrayList());//创建人选择意见
        map.put("cjrZgXzOpinion",Lists.newArrayList());//创建人主管选择意见
        map.put("csOpinion",Lists.newArrayList());// 技术负责人初审意见
        map.put("iprHsOpinion",Lists.newArrayList());// ipr互审意见
        map.put("zsOpinion",Lists.newArrayList());// 终审意见
        map.put("reviewOpinion",Lists.newArrayList());// 评审会初审意见

        List<Object> result = Lists.newArrayList();
        List<OpinionsAndFile> list = opinionMapper.getOpinions(disclosureId);
        for (OpinionsAndFile opinionsAndFile : list) {
            String nodeId = opinionsAndFile.getNodeId();
            switch (nodeId) {
                //主管审批意见
                case "19181F68A04841F2AE079A8D52925200":
                    opinionsAndFile.setName("主管意见");
                    map.get("zgOpinion").add(opinionsAndFile);
                    break;
                //单ipr 查新沟通给创建意见
                case "270BFB5523784223B122A3ABC5D40793":
                    opinionsAndFile.setName("查新意见");
                    map.get("cxOpinion").add(opinionsAndFile);
                    break;
                //多ipr 查新沟通给创建意见
                case "39DB703EDD0A4A20AF858FBBED6BF6ED":
                    opinionsAndFile.setName("查新意见");
                    map.get("cxOpinion").add(opinionsAndFile);
                    break;
                //创建人回复ipr意见
                case "6E7520D906344079B22229F1FB52E114":
                    map.get("cjrToIprOpinion").add(opinionsAndFile);
                    break;
                //创建人选择意见
                case "605EE45A7E024EAB8A790A16275706D6":
                    map.get("cjrXzOpinion").add(opinionsAndFile);
                    break;
                //创建人主管选择意见
                case "92F55916D90540C2B69A3014D97E2D3A":
                    map.get("cjrZgXzOpinion").add(opinionsAndFile);
                    break;
                //技术负责人初审选择意见
                case "673dae1bbd514caaa0841db1b539a3e3":
                    map.get("csOpinion").add(opinionsAndFile);
                    break;
                //ipr互审意见
                case "736ca4d2a36e475daefd92e9828a1489":
                    map.get("iprHsOpinion").add(opinionsAndFile);
                    break;
                // 评审会终审意见
                case "7524DFC3666B40C5A6E6EEFD063F06EA":
                    map.get("zsOpinion").add(opinionsAndFile);
                    break;
                //评审会初审
                case "97BF5B1F73414EA9BBDB55C62D46B981":
                    map.get("reviewOpinion").add(opinionsAndFile);
                    break;
            }
        }

        return map;
    }

    /**
     * 获取部门集合
     * @return
     */
    @Override
    public List<Map<String, Object>> getDeptAll() {
        return disclosureMapper.getDeptAll();
    }

    //    技术交底书
    @Override
    public List<Map<String, Object>> getTechnologyDisclosure(String disclosureId) {
        return disclosureMapper.getTechnologyDisclosure(disclosureId);
    }

    // 根据状态id 查询专利
    @Override
    public List<Disclosure> getDisclosureByStatusId(String statusId) {
        return disclosureMapper.getDisclosureByStatusId(statusId);
    }

    // ipr技术方案编写 查询交底书详细信息
    @Override
    public Map<String, Object> getDisclosureDetailPlanToWrite(String disclosureId) {

        Map<String, Object> map = disclosureMapper.getDisclosureDetailPlanToWrite(disclosureId);
        // 是否重要专利
        Integer significanceIdentify = StringUtils.toInteger(map.get("significanceIdentify"));
        String nodeId = "";
        // 重要专利
        if (significanceIdentify == 1) {
            nodeId = "39DB703EDD0A4A20AF858FBBED6BF6ED"; // 多个IPR查新
        }else if(significanceIdentify == 2){
            nodeId = "270BFB5523784223B122A3ABC5D40793"; // IPR查新
        }

        // 通过交底书id和节点id查询指派人列表
//        List<Map<String,Object>> list = workflowIdentitylinkMapper.findUsersByDisclosureIdAndNodeId(disclosureId,nodeId);
        List<Map<String, Object>> list = getDisclosureIpr(disclosureId);
        map.put("iprList",list);

        // 查询查新记录沟通
        List<String> nodeIds = Lists.newArrayList();
        nodeIds.add("003BFA10D8934DF992E34DED81787CCC");// 创建交底书
        nodeIds.add("39DB703EDD0A4A20AF858FBBED6BF6ED");// 多个IPR查新

        // 通过节点id和交底书id查新意见以及意见相关文件
        List<Map<String,Object>> maps = opinionMapper.getTextAndFileByNodeIdsAndDisclosureId(nodeIds,disclosureId);
        if (maps.size() == 0) {
            Map<String, Object> hashMap = Maps.newHashMap();
            hashMap.put("opinionText","无");
            hashMap.put("createdTime","无");
            hashMap.put("fullName","无");
            hashMap.put("fillName","无");
            maps.add(hashMap);
        }
        map.put("cxOpinion",maps);
        // 主管记录沟通
        List<String> zgNodeIds = Lists.newArrayList();
        zgNodeIds.add("19181F68A04841F2AE079A8D52925200");// 主管审核
        List<Map<String,Object>> zgMaps = opinionMapper.getTextAndFileByNodeIdsAndDisclosureId(zgNodeIds,disclosureId);
        if (zgMaps.size() == 0) {
            Map<String, Object> hashMap = Maps.newHashMap();
            hashMap.put("opinionText","无");
            hashMap.put("createdTime","无");
            hashMap.put("fullName","无");
            hashMap.put("fillName","无");
            zgMaps.add(hashMap);
        }
        //申请文件
        List<Integer> fileTypeList=new ArrayList<>();
        fileTypeList.add(1);
        List<Integer> checkTypeList=new ArrayList<>();
        checkTypeList.add(1);
        checkTypeList.add(0);
        List<PatentFile> listFile = patentFileMapper.getNewPatentFileByDiscId(disclosureId,fileTypeList,checkTypeList);
        if(listFile.size() != 0){
            map.put("patentFileList",listFile);
        }else{
            List<PatentFile> objects = Lists.newArrayList();
            map.put("patentFileList",objects);
        }

        map.put("zgOpinion",zgMaps);

        // 技术领域
        List<String> collect  = Arrays.asList(disclosureId);
        if(collect != null && collect.size() != 0) {
            Map<String,Map<String,String>> judgesById = judgesMapper.getJudgesById(collect);
            if (judgesById.containsKey(map.get("disclosureId"))) {
                map.put("judgesName",judgesById.get(map.get("disclosureId")).get("judgesName"));
            }

        }
        return map;
    }

    /**
     * 选择意见列表
     * @author 苏小林
     * @date 2020/2/26 13:52
     * @param: disclosureId
     * @return: java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     */
    @Override
    public List<Map<String, Object>> selectOpinion(String disclosureId) {
        return disclosureMapper.selectOpinion(disclosureId);
    }

    /**
     * 获取完整申请文件编写数据
     * @author 苏小林
     * @date 2020/2/26 17:29
     * @param: disclosureId
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     */
    @Override
    public Map<String, Object> getCompleteApplyFileData(String disclosureId) {
        Map<String, Object> map = this.getDisclosureDetailPlanToWrite(disclosureId);

        // 查询技术负责人初审意见
        List<String> nodeIds = Lists.newArrayList();
        nodeIds.add("673dae1bbd514caaa0841db1b539a3e3");// 负责人初审申请文件

        // 通过节点id和交底书id初审意见以及意见相关文件
        List<Map<String,Object>> maps = opinionMapper.getTextAndFileByNodeIdsAndDisclosureId(nodeIds,disclosureId);
        if (maps.size() == 0) {
            Map<String, Object> hashMap = Maps.newHashMap();
            hashMap.put("opinionText","无");
            hashMap.put("createdTime","无");
            hashMap.put("fullName","无");
            hashMap.put("fillName","无");
            maps.add(hashMap);
        }
        map.put("csOpinion",maps);//初审意见

        //查找完成的编写文件
        List<Integer> fileTypeList=new ArrayList<>();
        fileTypeList.add(3);
        List<Integer> checkTypeList=new ArrayList<>();
        checkTypeList.add(2);
        List<PatentFile> list = patentFileMapper.getNewPatentFileByDiscId(disclosureId,fileTypeList,checkTypeList);
        if(list.size() != 0){
            map.put("patentFileList",list);
        }else{
            List<PatentFile> objects = Lists.newArrayList();
            map.put("patentFileList",objects);

        }

        return map;
    }


    /**
     * 获取提交记录前查询专利数据
     * @author 苏小林
     * @date 2020/2/27 10:19
     * @param: disclosureId
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     */
    @Override
    public Map<String, Object> getBeforeSubmitRecordData(String disclosureId) {
        Map<String,Object> map = disclosureMapper.getBeforeSubmitRecordData(disclosureId);
        if (map !=null) {
            // 通过交底书id查询专利文件
            List<PatentFile> list = patentFileMapper.getPatentFileByDiscId(disclosureId,3,2);
            map.put("fileList",list);
        }

        return map;
    }


    /**
     * 发明人回复专利撰写人数据查询
     * @author 苏小林
     * @date 2020/2/27 10:51
     * @param: disclosureId
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     */
    @Override
    public Map<String, Object> inventorReplyCreateUser(String disclosureId) {
        Map<String, Object> map = disclosureMapper.getDisclosureDetailPlanToWrite(disclosureId);
        // 是否重要专利
        Integer significanceIdentify = StringUtils.toInteger(map.get("significanceIdentify"));
        String nodeId = "";
        // 重要专利
        if (significanceIdentify == 1) {
            nodeId = "39DB703EDD0A4A20AF858FBBED6BF6ED"; // 多个IPR查新
        }else if(significanceIdentify == 2){
            nodeId = "270BFB5523784223B122A3ABC5D40793"; // IPR查新
        }

        // 通过交底书id和节点id查询指派人列表
//        List<Map<String,Object>> list = workflowIdentitylinkMapper.findUsersByDisclosureIdAndNodeId(disclosureId,nodeId);
        List<Map<String, Object>> list = getDisclosureIpr(disclosureId);
        map.put("iprList",list);

        if (map !=null) {
            // 通过交底书id查询专利文件最新
            List<PatentFile> fileList = patentFileMapper.getPatentFileByDiscId(disclosureId,1,0);
            map.put("fileList",fileList);
        }

        return map;
    }


    /**
     * 获取交底书重新提交数据
     * @author 苏小林
     * @date 2020/3/2 15:38
     * @param: disclosureId
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     */
    @Override
    public Map<String, Object> getDisclosureResubmitData(String disclosureId) {
        Map<String, Object> map = disclosureMapper.getDisclosureDetailPlanToWrite(disclosureId);

        List<DisclosureInventor> inventorList = disclosureInventorMapper.getListByDisclosureId(disclosureId);

        map.put("inventorList",inventorList);
        // 文件列表
//        获取交底书的相关的文件
        List<PatentFile> fileList = patentFileMapper.getAllPatentFileByDiscId(disclosureId,0,0);
        map.put("fileList",fileList);
        // 技术领域
//        List<String> collect  = Arrays.asList(disclosureId);
//        if(collect != null && collect.size() != 0) {
//            Map<String,Map<String,String>> judgesById = judgesMapper.getJudgesById(collect);
//            if (judgesById.containsKey(disclosureId)) {
//                map.put("judgesName",judgesById.get(disclosureId).get("judgesName"));
//            }
//
//        }
        return map;
    }

    @Override
    public Disclosure getIprCxData(String disclosureId, Integer fileType) {
        Disclosure disclosure = disclosureMapper.getDisclosureByDisclosureId(disclosureId);
        if (disclosure !=null) {
            // 交底书
            List<PatentFile> list_0 = patentFileMapper.getPatentFileListByDiscId(disclosureId,0);
            // 查新报告
            List<PatentFile> list_1 = patentFileMapper.getPatentFileListByDiscId(disclosureId,4);
            list_0.addAll(list_1);
            disclosure.setPatentFileList(list_0);
            //建议IPR
            List<Long> strings = tbPamInventorProposalIprMapper.getAdviceIpr(disclosureId);
            disclosure.setInventorProposalIprs(strings);
            // 技术领域
//            List<String> collect  = Arrays.asList(disclosureId);
//            if(collect != null && collect.size() != 0) {
//                Map<String,Map<String,String>> judgesById = judgesMapper.getJudgesById(collect);
//                if (judgesById.containsKey(disclosure.getDisclosureId())) {
//                    disclosure.setJudgesName(judgesById.get(disclosure.getDisclosureId()).get("judgesName"));
//                }
//
//            }
        }
        return disclosure;
    }

    /**
     * 创建人回复IPR沟通记录
     * @author 苏小林
     * @date 2020/3/4 11:21
     * @param: disclosureId
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     */
    @Override
    public Map<String, Object> getCreatorReplyIprData(String disclosureId) {
        Map<String, Object> map = disclosureMapper.getDisclosureDetailPlanToWrite(disclosureId);

        List<DisclosureInventor> inventorList = disclosureInventorMapper.getListByDisclosureId(disclosureId);
        map.put("inventorList",inventorList);
        // 交底书
        List<PatentFile> fileList_0 = patentFileMapper.getPatentFileListByDiscId(disclosureId,0);
        // 查新报告
        List<PatentFile> fileList_1 = patentFileMapper.getPatentFileListByDiscId(disclosureId,4);
        fileList_0.addAll(fileList_1);
        map.put("fileList",fileList_0);

        List<Map<String, Object>> list = this.getDisclosureIpr(disclosureId);
        String ipsNames = "无";
        List<Long> ipsIds = Lists.newArrayList();
        if (list.size()>0) {
            StringBuilder iprName = new StringBuilder();
            for (Map<String, Object> stringObjectMap : list) {
                String fullName = String.valueOf(stringObjectMap.get("fullName"));
                Long userId = StringUtils.toLong(stringObjectMap.get("userId"));

                iprName.append(",");
                iprName.append(fullName);
                ipsIds.add(userId);
            }
            ipsNames = iprName.toString().substring(1);
        }

        map.put("ipsIds",ipsIds);
        map.put("ipsNames",ipsNames);

        return map;
    }

    // 获取交底书分配的ipr
    public List<Map<String,Object>> getDisclosureIpr(String disclosureId){
        try {
            List<Map<String,Object>> iprsList=tbPamInventorProposalIprMapper.getDisclosureIpr(disclosureId);
            return iprsList;
        }catch (Exception e){
            log.error("获取交底书分配的ipr异常",e);
            e.printStackTrace();
            return null;
        }
    }

    //    各个级别页面查看
    @Override
    public  Map<String, Object> getWorkFlowRecord(String disclosureId, Long createdUser, Long userId,String roleKeyname) {
        // 创建人的部门领导
        Long  users =userMapper.getLeaderId(createdUser);
        // 技术负责人用户id
        List<Long> leaderUserId = userMapper.getUserIdByRoleName(roleKeyname);
        // 指派的iprs
        List<Long> disclosureIprByDisclosureId = tbPamInventorProposalIprMapper.getUserIdByDisclosureId(disclosureId);
        // 流程专员
        List<Long> assistantUserId = userMapper.getUserIdByRoleName(assistantName);
        // 交底书相关数据
        Map<String, Object> map = disclosureMapper.getDisclosureDetailPlanToWrite(disclosureId);
        // 获取当前交底书评审会成员
        String judgesId = String.valueOf(map.get("judgesId"));
        Long patentUserId = null;
        if(StringUtils.isNotBlank(map.get("patentUserId")))
          patentUserId = Long.valueOf(String.valueOf(map.get("patentUserId")));
        Set<String> judgesUser = judgesUserMapper.getJudgesUser(judgesId);
        if (createdUser.equals(userId) || leaderUserId.contains(userId) || disclosureIprByDisclosureId.contains(userId)
                || userId.equals(users) || assistantUserId.contains(userId) || judgesUser.contains(userId)) {
            //  获取所有的交底书和最新的IPR上传的申请文件记录相关的文件
            map.put("fileList",getAllPatentFile(disclosureId));
        }
        // 当前用户是创建人也是技术负责人
        if(createdUser.equals(userId) && leaderUserId.contains(userId)){
            // 意见
            getAllOpinonAndFile(disclosureId,userId,map,0);
            // 我选择的重要性
            getJsOpinion(disclosureId,map);
            // 技术负责人选中文件
            getCheckOpinionByLeaderUseId(disclosureId,map);
        }
        //当前用户是创建人并且是ipr
        else if(createdUser.equals(userId) && disclosureIprByDisclosureId.contains(userId)){
            //意见
            getAllOpinonAndFile(disclosureId,userId,map,3);
        }
        //  当前用户是创建人且是部门领导
        else if(createdUser.equals(userId) && userId.equals(users)){
            getAllOpinonAndFile(disclosureId,userId,map,1);
         // 技术负责人
        }else if(leaderUserId.contains(userId)){
            getAllOpinonAndFile(disclosureId,userId,map,4);
           // 技术负责人辨识重要性
            getJsOpinion(disclosureId,map);
            //我选择的重要性
            getCheckOpinionByLeaderUseId(disclosureId,map);
        }
            // 当前用户是ipr
      else if(disclosureIprByDisclosureId.contains(userId)){
            getAllOpinonAndFile(disclosureId,userId,map,2);
        }
        // 当前用户是部门负责人
        else if(userId.equals(users)){
            getAllOpinonAndFile(disclosureId,userId,map,5);
        }
        else if(createdUser.equals(userId) || assistantUserId.contains(userId)){
            getAllOpinonAndFile(disclosureId,createdUser,map,6);
            getAllOpinonAndFile(disclosureId, patentUserId, map, 7);
          // 技术负责人辨识重要性
            getJsOpinion(disclosureId,map);
        }
        // 审批会退回意见
        if(judgesUser.contains(userId)) {
            getAllOpinonAndFile(disclosureId, patentUserId, map, 7);
        }else if(disclosureIprByDisclosureId.contains(userId)){
            getAllOpinonAndFile(disclosureId, userId, map, 7);
        }
        return map;
    }


    //当前用户所有的接收到的意见和回复的意见 和所有的审批意见
    public void getAllOpinonAndFile(String disclosureId, Long userId,Map<String, Object> map,int type ) {
        Map mapOpinion =new HashMap();
        mapOpinion.put("opinionText","无");
        mapOpinion.put("updateTime","无");
        mapOpinion.put("nodeId","无");
        mapOpinion.put("fileName","无");
        mapOpinion.put("url","无");
        mapOpinion.put("fullName","无");
        //当前用户所有的接收到的意见和回复的意见 和所有的审批意见
        List<Map<String, Object>> allOpinonAndFile = opinionMapper.getAllOpinonAndFile(disclosureId, userId);
        List<Map<String, Object>> zgOpinionList=new ArrayList<>();
        List<Map<String, Object>> iprOpinionList=new ArrayList<>();
        List<Map<String, Object>> createUserOpinionList=new ArrayList<>();
//        List<Map<String, Object>> createUserCheckList=new ArrayList<>();
        List<Map<String, Object>> createLeaderCheckOpinionList=new ArrayList<>();
        List<Map<String, Object>> leaderCheckOpinionList=new ArrayList<>();
        List<Map<String, Object>> iprToIprOpinionList=new ArrayList<>();
        List<Map<String, Object>> leaderFinaCheckOpinionList=new ArrayList<>();
        List<Map<String, Object>> closedCaseOpinionList=new ArrayList<>();
        List<Map<String, Object>> reviewOpinionList=new ArrayList<>();

        for (Map<String, Object> OpinonAndFile: allOpinonAndFile) {
            if("19181F68A04841F2AE079A8D52925200".equals(String.valueOf(OpinonAndFile.get("nodeId")))){
                //主管审批意见
                zgOpinionList.add(OpinonAndFile);
            }else if("8C337C68A0FF4F48B0B80C88B895868D".equals(String.valueOf(OpinonAndFile.get("nodeId")))){
                //主管退回创建人闭案意见
                closedCaseOpinionList.add(OpinonAndFile);
            }else if("39DB703EDD0A4A20AF858FBBED6BF6ED".equals(String.valueOf(OpinonAndFile.get("nodeId")))){
                //ipr 查新沟通给创建意见
                iprOpinionList.add(OpinonAndFile);
            }else if("003BFA10D8934DF992E34DED81787CCC".equals(String.valueOf(OpinonAndFile.get("nodeId")))){
                //创建人回复ipr意见
                createUserOpinionList.add(OpinonAndFile);
            }else if("736ca4d2a36e475daefd92e9828a1489".equals(String.valueOf(OpinonAndFile.get("nodeId")))){
                //ipr互审意见
                iprToIprOpinionList.add(OpinonAndFile);
            }else if("7524DFC3666B40C5A6E6EEFD063F06EA".equals(String.valueOf(OpinonAndFile.get("nodeId")))){
                //审批会终审意见
                leaderFinaCheckOpinionList.add(OpinonAndFile);
            }else  if("97BF5B1F73414EA9BBDB55C62D46B981".equals(String.valueOf(OpinonAndFile.get("nodeId")))){
                reviewOpinionList.add(OpinonAndFile); //审批会初审意见
            }
        }

        if(reviewOpinionList.size() == 0){
            reviewOpinionList.add(mapOpinion);
        }
        if(zgOpinionList.size() == 0){
            zgOpinionList.add(mapOpinion);
        }
        if(closedCaseOpinionList.size() == 0){
            closedCaseOpinionList.add(mapOpinion);
        }
        if(iprOpinionList.size() == 0){
            iprOpinionList.add(mapOpinion);
        }
        if(createUserOpinionList.size() == 0){
            createUserOpinionList.add(mapOpinion);
        }
//        if(createUserCheckList.size() == 0){
//            createUserCheckList.add(mapOpinion);
//        }
        if(createLeaderCheckOpinionList.size() == 0){
            createLeaderCheckOpinionList.add(mapOpinion);
        }
        if(leaderFinaCheckOpinionList.size() == 0){
            leaderFinaCheckOpinionList.add(mapOpinion);
        }

        if(type == 0){
            map.put("closedCaseOpinionList", closedCaseOpinionList);  //主管退回创建人闭案意见
            map.put("zgOpinion", zgOpinionList);  //主管审批意见
            map.put("iprOpinion", iprOpinionList); //ipr 查新沟通给创建意见
//            map.put("createLeaderCheckOpinion", createLeaderCheckOpinionList);  //创建人主管选择意见
            map.put("leaderCheckOpinion", leaderCheckOpinionList);  //技术负责人初审选择意见
//            map.put("leaderFinaCheckOpinion", leaderFinaCheckOpinionList); //技术负责人终审意见
        }else if(type == 1){
            map.put("closedCaseOpinionList", closedCaseOpinionList);  //主管退回创建人闭案意见
            map.put("zgOpinion", zgOpinionList);  //主管审批意见
            map.put("createUserOpinion", createUserOpinionList);  //创建人回复ipr意见
//            map.put("createUserCheckOpinion", createUserCheckList);  //创建人选择意见
        }else if(type == 2){
//            map.put("zgOpinion", zgOpinionList);  //主管审批意见
            map.put("iprOpinion", iprOpinionList); //ipr 查新沟通给创建意见
            map.put("createUserOpinion", createUserOpinionList);  //创建人回复ipr意见
//            map.put("createUserCheckOpinion", createUserCheckList);  //创建人选择意见
            map.put("leaderCheckOpinion", leaderCheckOpinionList);  //技术负责人初审选择意见
            map.put("iprToIprOpinion", iprToIprOpinionList);  //ipr互审意见
//            map.put("leaderFinaCheckOpinion", leaderFinaCheckOpinionList); //技术负责人终审意见
        }else if(type == 3){
            map.put("closedCaseOpinionList", closedCaseOpinionList);  //主管退回创建人闭案意见
            map.put("zgOpinion", zgOpinionList);  //主管审批意见
            map.put("iprOpinion", iprOpinionList); //ipr 查新沟通给创建意见
//            map.put("createUserOpinion", createUserOpinionList);  //创建人回复ipr意见
            map.put("leaderCheckOpinion", leaderCheckOpinionList);  //技术负责人初审选择意见
            map.put("iprToIprOpinion", iprToIprOpinionList);  //ipr互审意见
//            map.put("leaderFinaCheckOpinion", leaderFinaCheckOpinionList); //技术负责人终审意见
            map.put("reviewOpinionList", reviewOpinionList);  //退回意见
        }
        else if(type == 4){
            map.put("leaderCheckOpinion",leaderCheckOpinionList);  //技术负责人初审选择意见
//            map.put("leaderFinaCheckOpinion", leaderFinaCheckOpinionList); //技术负责人终审意见
        }
        else if(type == 5){
            map.put("zgOpinion", zgOpinionList);  //主管审批意见
//            map.put("createLeaderCheckOpinion", createLeaderCheckOpinionList);  //创建人主管选择意见
        }
        else if(type == 6){
            map.put("closedCaseOpinionList", closedCaseOpinionList);  //主管退回创建人闭案意见
            map.put("zgOpinion", zgOpinionList);  //主管审批意见
            map.put("iprOpinion", iprOpinionList); //ipr 查新沟通给创建意见
            map.put("createUserOpinion", createUserOpinionList);  //创建人回复ipr意见
//            map.put("createUserCheckOpinion", createUserCheckList);  //创建人选择意见
        }else if(type == 7){
            map.put("reviewOpinion", reviewOpinionList); //评审会初审意见和终审意见
            map.put("leaderFinaCheckOpinion", leaderFinaCheckOpinionList);
        }

//        map.put("zgOpinion", zgOpinionList);  //主管审批意见
//        map.put("iprOpinion", iprOpinionList); //ipr 查新沟通给创建意见
//        map.put("createUserOpinion", createUserOpinionList);  //创建人回复ipr意见
//        map.put("createUserCheckOpinion", createUserCheckList);  //创建人选择意见
//        map.put("createLeaderCheckOpinion", createLeaderCheckOpinionList);  //创建人主管选择意见
//        map.put("leaderCheckOpinion", leaderCheckOpinionList);  //技术负责人初审选择意见
//        map.put("iprToIprOpinion", iprToIprOpinionList);  //ipr互审意见
//        map.put("leaderFinaCheckOpinion", leaderFinaCheckOpinionList); //技术负责人终审意见

    }

    //获取所有的交底书文件
    public List<Map<String, Object>> getAllDisclosureFile(String disclosureId, String userId) {
        List<String> fileTypeList =new ArrayList<>();
        fileTypeList.add("0");
        return   patentFileMapper.getAllDisclosureFile(disclosureId, fileTypeList);
    }
    //获取最新的交底书文件
    public List<Map<String, Object>> getNewDisclosureFile(String disclosureId, String userId) {
        List<String> fileTypeList =new ArrayList<>();
        fileTypeList.add("0");
        return patentFileMapper.getNewDisclosureFile(disclosureId,fileTypeList);
    }
    //获取所有的申请文件
    public List<Map<String, Object>> getAllPatentFile(String disclosureId) {
        List<String> fileTypeList =new ArrayList<>();
        fileTypeList.add("0");
        fileTypeList.add("1");
        fileTypeList.add("2");
        fileTypeList.add("3");
        fileTypeList.add("4");
        return patentFileMapper.getAllDisclosureFile(disclosureId, fileTypeList);
    }

    //获取当前ipr所编写的申请文件
    public List<Map<String, Object>> getAllPatentFileByIpr(String disclosureId, String userId) {
        List<String> fileTypeList =new ArrayList<>();
        fileTypeList.add("1");
        fileTypeList.add("2");
        return   patentFileMapper.getAllPatentFileByIpr(disclosureId, fileTypeList,userId);
    }

    //获取最新的申请文件
    public List<Map<String, Object>> getNewPatentFile(String disclosureId, String userId) {
        List<String> fileTypeList =new ArrayList<>();
        fileTypeList.add("1");
        fileTypeList.add("2");
        return patentFileMapper.getNewDisclosureFile(disclosureId,fileTypeList);
    }

    //技术负责人辨识重要性
    public void getJsOpinion(String disclosureId, Map<String, Object> map) {
        //分配的ipr
        List<Map<String, Object>> list = this.getDisclosureIpr(disclosureId);
        String ipsNames = "无";
        String ipsIds = "";
        if (list.size()>0) {
            StringBuilder iprName = new StringBuilder();
            StringBuilder iprId = new StringBuilder();
            for (Map<String, Object> stringObjectMap : list) {
                String fullName = String.valueOf(stringObjectMap.get("fullName"));
                String userId = String.valueOf(stringObjectMap.get("userId"));
                iprName.append(",");
                iprName.append(fullName);
                iprId.append(",");
                iprId.append(userId);
            }
            ipsNames = iprName.toString().substring(1);
            ipsIds = iprId.toString().substring(1);
        }
        map.put("ipsIds",ipsIds);
        map.put("ipsNames",ipsNames);

    }

    //    技术负责人选中文件
    public void getCheckOpinionByLeaderUseId(String disclosureId, Map<String, Object> map) {

        List<Map<String, Object>> checkOpinionByLeaderUseId = patentFileMapper.getCheckOpinionByLeaderUseId(disclosureId);
        if(checkOpinionByLeaderUseId.size() == 0){
             Map<String, Object> checkFile = new HashMap<>();
            checkFile.put("fileName","无");
            checkFile.put("url","无");
            checkOpinionByLeaderUseId.add(checkFile);
        }
        map.put("checkFile",checkOpinionByLeaderUseId);
    }


    //    多人审核申请文件列表
    @Override
    public List<Map<String, Object>> getManyPeopleFile(String disclosureId) {
        return patentFileMapper.getManyPeopleFile(disclosureId,1);
    }

    //    多人审核查看页面
    @Override
    public  Map<String, Object> getManyPeopleExamineData(String disclosureId, String userId, String patentFileId,String type) {
      //获取交底书
        Map<String, Object> map = disclosureMapper.getDisclosureDetailPlanToWrite(disclosureId);
        //申请文件
        List<Map<String, Object>> patentFileByPatentFileId = patentFileMapper.getPatentFileByPatentFileId(disclosureId,patentFileId);
        if(patentFileByPatentFileId.size()!=0){
            map.put("fileList", patentFileByPatentFileId);
        }
        //对申请文件的意见
        //当前用户对此文件的评论
      List<Map<String,Object>> textAndFileByNodeId=opinionMapper.getTextAndFileByNodeId(disclosureId,userId,patentFileId);
        if(textAndFileByNodeId.size()!=0){
            map.put("currentUserOpinion",textAndFileByNodeId);
    }
        if( "1".equals(type)){
            // 发明人填写选择意见
            List<String> nodeIds = Lists.newArrayList();
            nodeIds.add("605EE45A7E024EAB8A790A16275706D6");// 发明人填写选择意见
            List<Map<String,Object>> maps = opinionMapper.getTextAndFileByNodeIdsAndPatentFileId(nodeIds,disclosureId,patentFileId);
            if(maps.size()==0){
                Map mapOpinion =new HashMap();
                mapOpinion.put("opinionText","无");
                mapOpinion.put("createdTime","无");
                mapOpinion.put("fileName","无");
                mapOpinion.put("url","无");
                mapOpinion.put("fullName","无");
                maps.add(mapOpinion);
            }
            map.put("inventorOpinion",maps);
             // 发明人主管填写选择意见
            List<String> nodeIds1 = Lists.newArrayList();
            nodeIds1.add("92F55916D90540C2B69A3014D97E2D3A");// 发明人主管填写选择意见
            //  对此文件的评论
            List<Map<String,Object>> maps1 = opinionMapper.getTextAndFileByNodeIdsAndPatentFileId(nodeIds1,disclosureId,patentFileId);
            if(maps1.size()==0){
                Map mapOpinion =new HashMap();
                mapOpinion.put("opinionText","无");
                mapOpinion.put("createdTime","无");
                mapOpinion.put("fileName","无");
                mapOpinion.put("url","无");
                mapOpinion.put("fullName","无");
                maps1.add(mapOpinion);
            }
            map.put("inventorDirectorOpinion",maps1);
            //技术负责人的意见
        }

        return map;
    }

    //获取节点状态
    @Override
    public List<Map<String,Object>> getPhaseStatus() {
        List<Map<String,Object>> phaseStatus = workflowNodeMapper.getPhaseStatus();
        return  phaseStatus;
    }

    @Override
    public Integer disclosureTotalByType(String type, String typeParam,String typeKinds) {
            List<String> nodeList=new ArrayList<>();
            nodeList.add("003BFA10D8934DF992E34DED81787CCC");
        return disclosureMapper.disclosureTotalByType(type,typeParam,typeKinds,nodeList);
    }

    //报表饼状图
    @Override
    public List<Map<String, Object>> getPieNumData(Map<String,Object> param) {
        Object startTime= param.get("startTime");
        Object endTime=   param.get("endTime");
        // 报表饼状图
        List<Map<String, Object>> mapList= disclosureMapper.getPieNumDataByRunExec(startTime,endTime);
        Collections.sort(mapList,new Comparator<Map<String, Object>>(){
            //升序排序
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                Integer phaseStatus1 = Integer.parseInt(String.valueOf(o1.get("phaseStatus")));
                Integer phaseStatus2 = Integer.parseInt(String.valueOf(o2.get("phaseStatus")));
                //使用Entry类中的值来比较大小
                return phaseStatus2.compareTo(phaseStatus1);//s1在前面是升序,s1在后面是降序
            }
        });
        List<Map<String, Object>> numMap=new ArrayList<>();
        int dvalue=0;
        int qvalue=0;
        for (Map<String, Object> num: mapList){
            // 阶段为初审待审规划为交底书
            if ("10".equals(String.valueOf(num.get("phaseStatus")))){
                dvalue=Integer.parseInt(String.valueOf(num.get("value")));
            }
            if ("3".equals(String.valueOf(num.get("phaseStatus")))){
                num.put("value",Integer.parseInt(String.valueOf(num.get("value"))) + dvalue);
            }
            // 阶段为终审待审规划为权利要求文件
            if ("11".equals(String.valueOf(num.get("phaseStatus")))){
                qvalue=Integer.parseInt(String.valueOf(num.get("value")));
            }
            if ("4".equals(String.valueOf(num.get("phaseStatus")))){
                num.put("value",Integer.parseInt(String.valueOf(num.get("value"))) + qvalue);
            }
            if (!"10".equals(String.valueOf(num.get("phaseStatus"))) && !"11".equals(String.valueOf(num.get("phaseStatus")))) {
                numMap.add(num);
            }
        }
        Collections.sort(numMap,new Comparator<Map<String, Object>>(){
            //降序排序
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                Integer phaseStatus1 = Integer.parseInt(String.valueOf(o1.get("phaseStatus")));
                Integer phaseStatus2 = Integer.parseInt(String.valueOf(o2.get("phaseStatus")));
                //使用Entry类中的值来比较大小
                return phaseStatus1.compareTo(phaseStatus2);//s1在前面是升序,s1在后面是降序
            }
        });
        return numMap;
    }

//    保存回复评审会意见
    @Override
    public Message replayJudgesOpinion(TbPamJudgesReviewRecord tbPamJudgesReviewRecord) {
        Date date = new Date();
        tbPamJudgesReviewRecord.setReplyTime(date);
        tbPamJudgesReviewRecord.setUpdateDate(date);
        tbPamJudgesReviewRecord.setUpdateBy(tbPamJudgesReviewRecord.getRepliedBy());
        if(judgesReviewRecordMapper.updateById(tbPamJudgesReviewRecord)!=1) {
           TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//关键
           return Message.error(1,"修改回复反馈意见相关信息错误");
       }
        List<TbPamJudgesReviewRecordFile> tbPamJudgesReviewRecordFileList = tbPamJudgesReviewRecord.getTbPamJudgesReviewRecordFileList();
        for (TbPamJudgesReviewRecordFile file:tbPamJudgesReviewRecordFileList) {
            file.setId(IdGen.generateUUID());
            file.setType(1);
            file.setCreateDate(date);
            file.setUpdateDate(date);
            file.setUploadTime(date);
            file.setReviewRecordId(tbPamJudgesReviewRecord.getId());
            file.setCreateBy(tbPamJudgesReviewRecord.getRepliedBy());
            file.setUpdateBy(tbPamJudgesReviewRecord.getRepliedBy());
            if(tbPamJudgesReviewRecordFileMapper.insert(file)!=1) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//关键
                return Message.error(1,"保存回复反馈意见文件相关信息错误");
            }
        }
        return Message.success("成功");
    }

    //报表饼状图
    public List<Map<String, Object>> getPieNumData2(Object startTime, Object endTime) {
        List<String> nodeList=new ArrayList<>();
        nodeList.add("97BF5B1F73414EA9BBDB55C62D46B981");
        nodeList.add("7524DFC3666B40C5A6E6EEFD063F06EA");
        Map<String, Object>  phaseStatusNumList = new HashMap<>();
        List<Map<String, Object>> numMap= disclosureMapper.getPieNumData(startTime,endTime,nodeList);
            //数据授权通过
        Map<String, Object> numMapByAuthorizedPass=disclosureMapper.getNumMapByAuthorizedPass(startTime,endTime);
        //权力要求文件  查新通过是权力要求文件 但需要注意查新沟通
        List<String> nodeList1=new ArrayList<>();
        nodeList1.add("6E7520D906344079B22229F1FB52E114");
        nodeList1.add("39DB703EDD0A4A20AF858FBBED6BF6ED");
        nodeList1.add("270BFB5523784223B122A3ABC5D40793");
        List<Integer> phaseStatusList1 = new ArrayList<>();
        phaseStatusList1.add(4);
        List<Map<String, Object>> numMapByPhaseStatus= disclosureMapper.getPieNumDataByPhaseStatus(startTime,endTime,phaseStatusList1,nodeList1);
        for (Map<String, Object> num : numMapByPhaseStatus
             ) {
            numMap.add(num);
        }

        Map map=new HashMap();
        for ( Map<String, Object> num: numMap
        ) {
            //授权通过
            if(num.get("name").equals(numMapByAuthorizedPass.get("name"))){
                num.replace("name",numMapByAuthorizedPass.get("name"));
                num.replace("value",numMapByAuthorizedPass.get("value"));
                num.replace("phaseStatus",numMapByAuthorizedPass.get("phaseStatus"));
            }
            phaseStatusNumList.put(String.valueOf(num.get("name")),numMapByAuthorizedPass.get("phaseStatus"));
        }
        if(map.size()!=0) {
            numMap.add(map);
        }

        List<Map<String,Object>> phaseStatusList = getPhaseStatus();
        for (Map<String,Object> phaseStatus: phaseStatusList
        ) {
            if(!phaseStatusNumList.containsKey(String.valueOf(phaseStatus.get("label")))) {
                Map phaseStatusMap = new HashMap();
                phaseStatusMap.put("name", String.valueOf(phaseStatus.get("label")));
                phaseStatusMap.put("value", 0);
                phaseStatusMap.put("phaseStatus", String.valueOf(phaseStatus.get("value")));
                numMap.add(phaseStatusMap);
            }
        }
        Collections.sort(numMap,new Comparator<Map<String, Object>>(){
            //降序排序
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                Integer phaseStatus1 = Integer.parseInt(String.valueOf(o1.get("phaseStatus")));
                Integer phaseStatus2 = Integer.parseInt(String.valueOf(o2.get("phaseStatus")));
                //使用Entry类中的值来比较大小
                return phaseStatus1.compareTo(phaseStatus2);//s1在前面是升序,s1在后面是降序
            }
        });
        return numMap;
    }


    //饼状图数据
    @Override
    public List<Map<String, Object>> getNumData(String typeParam, int type) {
        List<Map<String, Object>> numMap = new ArrayList<>();
        Map<String, Object>  numMapByAuthorizedPass = new HashMap<>();
        Map<String, Object>  phaseStatusNumList = new HashMap<>();
        if(type == 0) {
            //数据按月度
            numMap=disclosureMapper.getNumByMonth(typeParam);
//            数据按月度授权通过
            numMapByAuthorizedPass=disclosureMapper.getNumMapByAuthorizedPassMonth(typeParam);
        }else if(type == 1){
//            数据按季度
            numMap=  disclosureMapper.getNumByQuarter(typeParam);
            //            数据按季度授权通过
            numMapByAuthorizedPass=disclosureMapper.getNumMapByAuthorizedPassQuarter(typeParam);

        }else if(type == 2){
            //            数据按年
            numMap=disclosureMapper.getNumByYear(typeParam);
            //            数据按年授权通过
            numMapByAuthorizedPass=disclosureMapper.getNumMapByAuthorizedPassYear(typeParam);
        }
        Map map=new HashMap();
        for ( Map<String, Object> num: numMap
        ) {
            //授权通过
            if(num.get("name").equals(numMapByAuthorizedPass.get("name"))){
                num.replace("name",numMapByAuthorizedPass.get("name"));
                num.replace("value",numMapByAuthorizedPass.get("value"));
                num.replace("phaseStatus",numMapByAuthorizedPass.get("phaseStatus"));
            }
            phaseStatusNumList.put(String.valueOf(num.get("name")),numMapByAuthorizedPass.get("phaseStatus"));
        }
        if(map.size()!=0) {
            numMap.add(map);
        }

        List<Map<String,Object>> phaseStatusList = getPhaseStatus();
        for (Map<String,Object> phaseStatus: phaseStatusList
        ) {
            if(!phaseStatusNumList.containsKey(String.valueOf(phaseStatus.get("label")))) {
                Map phaseStatusMap = new HashMap();
                phaseStatusMap.put("name", String.valueOf(phaseStatus.get("label")));
                phaseStatusMap.put("value", 0);
                phaseStatusMap.put("phaseStatus", String.valueOf(phaseStatus.get("value")));
                numMap.add(phaseStatusMap);
            }
        }
        Collections.sort(numMap,new Comparator<Map<String, Object>>(){
            //降序排序
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                Integer phaseStatus1 = Integer.parseInt(String.valueOf(o1.get("phaseStatus")));
                Integer phaseStatus2 = Integer.parseInt(String.valueOf(o2.get("phaseStatus")));
                //使用Entry类中的值来比较大小
                return phaseStatus1.compareTo(phaseStatus2);//s1在前面是升序,s1在后面是降序
            }
        });

        return numMap;
    }

//    报表柱状图个人
    @Override
    public List<Map<String, Object>> getNumDataByUser(String typeParam, String typeKinds, int type) {
        List<Map<String, Object>> numMap = new ArrayList<>();
        // 交底书报表柱状重要与不重要
        List<String> nodeIdList=new ArrayList<>();
        switch (typeKinds){
            case "3":
                nodeIdList.add("003BFA10D8934DF992E34DED81787CCC");
                break;
            case "4":
                nodeIdList.add("3AE5CBF5E43E444D8256929EC6BFF2C8");
                break;
            case "5":
                nodeIdList.add("67409ADFDC384E46AA3F6B410113E495");
                break;
            case "6":
                nodeIdList.add("D83445C2BFAA4B1CBA275DD1640D3EFE");
                break;
            case "7":
                nodeIdList.add("88A4B87FDF314252902F8FA65B2358BC");
                break;
            case "8":
                nodeIdList.add("88c90b93b2894fe5bd17bb7e3dca6f24");
                break;
            case "9":
                nodeIdList.add("253CBECAAB5342CBA4EFC3FE56B1F34C");
                break;
        }
        if("3".equals(typeKinds)){
            numMap=disclosureMapper.getNumDataByDisclosureSignificanceIdentify(type,typeParam,nodeIdList);
        }else{
            numMap=disclosureMapper.getNumDataByUserBySignificanceIdentify(type,typeParam,nodeIdList);
        }
        return numMap;
    }

//    根据报表得到对应的全部数据二级
    @Override
    public List<Map<String, Object>> getDatasByUser(String userId, String typeKinds, int type) {
        List<Map<String, Object>> numMap = new ArrayList<>();
        List<String> nodeIdList=new ArrayList<>();
        switch (typeKinds){
            case "3":
                nodeIdList.add("003BFA10D8934DF992E34DED81787CCC");
                break;
            case "4":
                nodeIdList.add("3AE5CBF5E43E444D8256929EC6BFF2C8");
                break;
            case "5":
                nodeIdList.add("67409ADFDC384E46AA3F6B410113E495");
                break;
            case "6":
                nodeIdList.add("D83445C2BFAA4B1CBA275DD1640D3EFE");
                break;
            case "7":
                nodeIdList.add("88A4B87FDF314252902F8FA65B2358BC");
                break;
            case "8":
                nodeIdList.add("88c90b93b2894fe5bd17bb7e3dca6f24");
                break;
            case "9":
                nodeIdList.add("253CBECAAB5342CBA4EFC3FE56B1F34C");
                break;
        }

        if("3".equals(typeKinds)){
            numMap=disclosureMapper.getNumByDisclosureByUserId(type,userId,nodeIdList);
        }else{
            numMap=disclosureMapper.getNumByUserId(type,userId,nodeIdList);
        }
        return numMap;
    }


    //    交底书所有数据总数
    @Override
    public int getDisclosureTotal() {
        return disclosureMapper.getDisclosureTotal();
    }


    /**
     * 查询初审数据
     * @author 苏小林
     * @date 2021/1/11 15:43
     * @param: disclosureId 
     * @return: com.xhsj.user.pms.patent.domain.Disclosure
     */
    @Override
    public Disclosure getFirstTrialData(String disclosureId,Integer fileType) {
        // 查询交底书
        Disclosure disclosure = disclosureMapper.getDisclosureByDisclosureId(disclosureId);
        if (disclosure != null) {
            // 查询最新的文件
            List<PatentFile> list = patentFileMapper.getLatestFileByFileType(disclosureId,fileType);
            disclosure.setPatentFileList(list);
            // 技术领域
            List<String> collect  = Arrays.asList(disclosureId);
            if(collect != null && collect.size() != 0) {
                Map<String,Map<String,String>> judgesById = judgesMapper.getJudgesById(collect);
                if (judgesById.containsKey(disclosure.getDisclosureId())) {
                    disclosure.setJudgesName(judgesById.get(disclosure.getDisclosureId()).get("judgesName"));
                }

            }
        }
        return disclosure;
    }

    @Override
    public List<TransferPCTOrPRCDataQuery> getTransferPCTOrPRCData(List<TransferPCTOrPRCDataDto> data) {
        List<TransferPCTOrPRCDataQuery> transferPCTOrPRCData = disclosureMapper.getTransferPCTOrPRCData();
        data.forEach((value)->{
            transferPCTOrPRCData.forEach(item->{
                if ((Objects.equals(item.getNodeId(),value.getKey().getNodeId()) &&
                        !value.getKey().getDisclosureId().contains(item.getDisclosureId()) &&
                        !value.getKey().getArchivesNum().contains(item.getArchivesNum()))
                        || (value.getKey().getDisclosureId().contains(item.getDisclosureId()) &&
                        StringUtils.isBlank(value.getKey().getNodeId()))
                        || (value.getKey().getArchivesNum().contains(item.getArchivesNum()) &&
                        StringUtils.isBlank(value.getKey().getNodeId()))) {
                        this.saveMigrateData(value,item);
                }
            });
                });
        return transferPCTOrPRCData;
    }

    public void saveMigrateData(TransferPCTOrPRCDataDto value,TransferPCTOrPRCDataQuery item){
        // 添加申请表
        TbPamOverseasApply apply = new TbPamOverseasApply();;
        BeanUtils.copyProperties(value.getApply(),apply);
        // 交底书id
        apply.setDisclosureId(StringUtils.isBlank(apply.getDisclosureId())?item.getDisclosureId():apply.getDisclosureId());
        // 国内案件案卷号
        apply.setArchivesNum(StringUtils.isBlank(apply.getArchivesNum())?item.getArchivesNum():apply.getArchivesNum());
        // 海外案件申请名称
        apply.setName(StringUtils.isBlank(apply.getName())?item.getName():apply.getName());
        // 实现点
        apply.setRegionalDetailsId(new Long(2));
        // 优先权号
        apply.setPriorityNum(StringUtils.isBlank(apply.getPriorityNum())?item.getPriorityNum():apply.getPriorityNum());
        // 优先权日
        apply.setPriorityDate(StringUtils.isBlank(apply.getPriorityDate())?item.getPriorityDate():apply.getPriorityDate());
        // 优先权届满日
        Date priorityDate = item.getPriorityDate();
        if (StringUtils.isBlank(apply.getPriorityApplyExpiration()) && StringUtils.isNotBlank(priorityDate)) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(priorityDate);
            calendar.add(Calendar.MONTH, 30);
            apply.setPriorityApplyExpiration(calendar.getTime());
        }
        // 获取申请号和公开号和专利表id
        if(StringUtils.isNotBlank(apply.getDomesticTreeValue())) {
            ApplyNumAndPublicNumQuery applyNumAndPublicNum = dao.getApplyNumAndPublicNum(item.getNum());
            if (applyNumAndPublicNum != null) {
                String applicationNum = applyNumAndPublicNum.getApplicationNum() == null ? "" : applyNumAndPublicNum.getApplicationNum();
                apply.setDomesticTreeValue(applicationNum);
                apply.setPatentId(StringUtils.isBlank(apply.getPatentId()) ? applyNumAndPublicNum.getPatentId() : apply.getPatentId());
            }
        }
        // ipr
        // 获取对应的交底书ipr
        List<Long> adviceIpr = tbPamInventorProposalIprMapper.getAdviceIpr(item.getDisclosureId());
        if (adviceIpr.size()>0)
            apply.setIpr(StringUtils.isBlank(apply.getIpr())?adviceIpr.get(0):apply.getIpr());
        if(apply.getNodeId()>2 && StringUtils.isBlank(apply.getIpr()))
            throw new NullPointerException("IPR不能为空");
        // 添加对应的1.在先申请文件
        boolean isApplyFile=false;
        boolean isApplyFile2=false;
        boolean isApplyFile3=false;
        List<TbPamOverseasApplyFile> applyFileList=new ArrayList<>(apply.getApplyFileList());
        if(StringUtils.isBlank(applyFileList)) {
            tbPamOverseasApplyService.getDomesticApplyFile(item.getDisclosureId(),applyFileList);
        }else{
            for (TbPamOverseasApplyFile tbPamOverseasApplyFile : applyFileList) {
                if (tbPamOverseasApplyFile.getFileType()==1) {
                    isApplyFile=true;
                }

                if (tbPamOverseasApplyFile.getFileType()==2) {
                    isApplyFile2=true;
                }

                if (tbPamOverseasApplyFile.getFileType()==3) {
                    isApplyFile3=true;
                }
            }
            if(apply.getNodeId()>3 && apply.getNodeId() != 10 && apply.getNodeId() != 11 && !isApplyFile2)
                throw new NullPointerException("完整申请文件不能为空");
            if(apply.getNodeId()>6 && apply.getNodeId() != 10 && apply.getNodeId() != 11 && !isApplyFile3)
                throw new NullPointerException("委托/提交文件不能为空");
            if (!isApplyFile) {
                tbPamOverseasApplyService.getDomesticApplyFile(item.getDisclosureId(),applyFileList);
            }
        }
        apply.setApplyFileList(applyFileList);

        List<TbPamOverseasApplyCountryDto> countryList = value.getCountry();
        // 判断是否迁徙到节点1 10 11
        // 添加对应的国家历史表
        List<String> listc = new ArrayList<>();
        List<String> listc1 = new ArrayList<>();
        if(countryList!=null ){
            boolean isSpecialCountry=false;
            for(TbPamOverseasApplyCountryDto country:countryList){
                TbPamOverseasApplyCountryDto tbPamOverseasApplyCountry=new TbPamOverseasApplyCountryDto();
                if(StringUtils.isNotBlank(country.getDisclosureId())&&
                        Objects.equals(country.getDisclosureId(),item.getDisclosureId())){
                    BeanUtils.copyProperties(country,tbPamOverseasApplyCountry);
                    isSpecialCountry=true;
                    tbPamOverseasApplyCountry.setCreateDate(tbPamOverseasApplyCountry.getCreateDate()==null?new Date():tbPamOverseasApplyCountry.getCreateDate());
                    tbPamOverseasApplyCountry.setUpdateDate(tbPamOverseasApplyCountry.getUpdateDate()==null?new Date():tbPamOverseasApplyCountry.getUpdateDate());
                    tbPamOverseasApplyCountry.setCreateBy(tbPamOverseasApplyCountry.getCreateBy()==null? UserUtils.getLoginAppUser().getUserId():tbPamOverseasApplyCountry.getCreateBy());
                    tbPamOverseasApplyCountry.setUpdateBy(tbPamOverseasApplyCountry.getUpdateBy()==null?UserUtils.getLoginAppUser().getUserId():tbPamOverseasApplyCountry.getUpdateBy());
                    if(apply.getNodeId() != 10 && apply.getNodeId() != 11) {
                        try {
                            apply.setId(null);
                            tbPamOverseasApplyService.saveData(apply);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        tbPamOverseasApplyCountry.setDataId(apply.getId());
                        if (tbPamOverseasApplyCountryMapper.insert(tbPamOverseasApplyCountry) != 1)
                            try {
                                throw new Exception("添加对应的国家异常");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        savaHitask(value, apply, item);
                    }
                    listc.add(country.getCountryName());
                }

            };
            if(!isSpecialCountry)
                for(TbPamOverseasApplyCountryDto country:countryList) {
                    if (StringUtils.isBlank(country.getDisclosureId())) {
                        TbPamOverseasApplyCountryDto tbPamOverseasApplyCountry = new TbPamOverseasApplyCountryDto();
                        BeanUtils.copyProperties(country, tbPamOverseasApplyCountry);
                        tbPamOverseasApplyCountry.setDataId(apply.getId());
                        tbPamOverseasApplyCountry.setCreateDate(tbPamOverseasApplyCountry.getCreateDate() == null ? new Date() : tbPamOverseasApplyCountry.getCreateDate());
                        tbPamOverseasApplyCountry.setUpdateDate(tbPamOverseasApplyCountry.getUpdateDate() == null ? new Date() : tbPamOverseasApplyCountry.getUpdateDate());
                        tbPamOverseasApplyCountry.setCreateBy(tbPamOverseasApplyCountry.getCreateBy() == null ? UserUtils.getLoginAppUser().getUserId() : tbPamOverseasApplyCountry.getCreateBy());
                        tbPamOverseasApplyCountry.setUpdateBy(tbPamOverseasApplyCountry.getUpdateBy() == null ? UserUtils.getLoginAppUser().getUserId() : tbPamOverseasApplyCountry.getUpdateBy());
                        if(apply.getNodeId() != 10 && apply.getNodeId() != 11) {
                            try {
                                apply.setId(null);
                                this.saveMigrateApply(apply);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            tbPamOverseasApplyCountry.setDataId(apply.getId());
                            if (tbPamOverseasApplyCountryMapper.insert(tbPamOverseasApplyCountry) != 1)
                                try {
                                    throw new Exception("添加对应的国家异常");
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            savaHitask(value, apply, item);
                        }
                        listc1.add(tbPamOverseasApplyCountry.getCountryName());
                    }
                }
        }
        if(apply.getNodeId() == 10 || apply.getNodeId() == 11) {
            String contryString = null;
            if (listc != null && listc.size() != 0) {
                  contryString = String.join(",", listc);
            }
            if (listc1 != null && listc1.size() != 0) {
                contryString = String.join(",", listc1);
            }
                TbPamGeneralProcessHiTask hiTask = value.getHiTask();
                if(StringUtils.isBlank(value.getHiTask())) {
                    hiTask = new TbPamGeneralProcessHiTask();
                    hiTask.setUserId(value.getTask().getUserId());
                    hiTask.setRoleId(value.getTask().getRoleId());
                    hiTask.setNodeId(value.getTask().getNodeId());
                }

                hiTask.setRemarks(contryString);
                value.setHiTask(hiTask);
                try {
                    tbPamOverseasApplyService.saveData(apply);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                savaHitask(value, apply, item);
                if(value.getTask().getNodeId() == 11 && countryList!=null) {
                    TbPamOverseasApplyCountry tbPamOverseasApplyCountry = new TbPamOverseasApplyCountry();
                    tbPamOverseasApplyCountry.setDataId(apply.getId());
                    tbPamOverseasApplyCountry.setCountryName(contryString);
                    tbPamOverseasApplyCountry.setCreateDate(tbPamOverseasApplyCountry.getCreateDate() == null ? new Date() : tbPamOverseasApplyCountry.getCreateDate());
                    tbPamOverseasApplyCountry.setUpdateDate(tbPamOverseasApplyCountry.getUpdateDate() == null ? new Date() : tbPamOverseasApplyCountry.getUpdateDate());
                    tbPamOverseasApplyCountry.setCreateBy(tbPamOverseasApplyCountry.getCreateBy() == null ? UserUtils.getLoginAppUser().getUserId() : tbPamOverseasApplyCountry.getCreateBy());
                    tbPamOverseasApplyCountry.setUpdateBy(tbPamOverseasApplyCountry.getUpdateBy() == null ? UserUtils.getLoginAppUser().getUserId() : tbPamOverseasApplyCountry.getUpdateBy());
                    if(tbPamOverseasApplyCountryMapper.insert(tbPamOverseasApplyCountry) !=1)
                        try {
                            throw new Exception("添加对应的国家异常");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                }

        }

        // 保存专利模块国内案件提示信息
        TbPamOverseasPrompt tbPamOverseasPrompt = new TbPamOverseasPrompt();
        tbPamOverseasPrompt.setDisclosureId(item.getDisclosureId());
        tbPamOverseasPrompt.setRegionalDetailsId(new Long(2));
        if (!tbPamOverseasPromptService.save(tbPamOverseasPrompt)) {
            try {
                throw new Exception("保存专利模块国内案件提示信息异常");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
        public void savaHitask(TransferPCTOrPRCDataDto value,TbPamOverseasApply apply,TransferPCTOrPRCDataQuery item){
            // 添加任务表
            TbPamGeneralProcessTask task=new TbPamGeneralProcessTask();
            if(StringUtils.isNotBlank(value.getTask())){
                BeanUtils.copyProperties(value.getTask(),task);
                task.setDataId(apply.getId());
                task.setProcessType(StringUtils.isBlank(task.getProcessType())?"foreign_apply":task.getProcessType());
                task.setCreateDate(task.getCreateDate()==null?new Date():task.getCreateDate());
                task.setUpdateDate(task.getUpdateDate()==null?new Date():task.getUpdateDate());
                task.setCreateBy(task.getCreateBy()==null? UserUtils.getLoginAppUser().getUserId():task.getCreateBy());
                task.setUpdateBy(task.getUpdateBy()==null?UserUtils.getLoginAppUser().getUserId():task.getUpdateBy());
                if(tbPamGeneralProcessTaskMapper.insert(task)!=1)
                    try {
                        throw new Exception("添加任务表异常");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
            }
            // 添加历史任务表
            TbPamGeneralProcessHiTask hiTask = new TbPamGeneralProcessHiTask();
            if(StringUtils.isBlank(value.getHiTask()))
                BeanUtils.copyProperties(task,hiTask);
            else {
                BeanUtils.copyProperties(value.getHiTask(), hiTask);
                hiTask.setDataId(apply.getId());
            }
            if(StringUtils.isNotBlank(hiTask)) {
                hiTask.setExamineStatus(StringUtils.isBlank(hiTask.getExamineStatus())?0:hiTask.getExamineStatus());
                hiTask.setProcessType(StringUtils.isBlank(task.getProcessType())?"foreign_apply":task.getProcessType());
                hiTask.setCreateDate(hiTask.getCreateDate()==null?new Date():hiTask.getCreateDate());
                hiTask.setUpdateDate(hiTask.getUpdateDate()==null?new Date():hiTask.getUpdateDate());
                hiTask.setCreateBy(hiTask.getCreateBy()==null? UserUtils.getLoginAppUser().getUserId():hiTask.getCreateBy());
                hiTask.setUpdateBy(hiTask.getUpdateBy()==null?UserUtils.getLoginAppUser().getUserId():hiTask.getUpdateBy());
                if (tbPamGeneralProcessHiTaskMapper.insert(hiTask) != 1)
                    try {
                        throw new Exception("添加历史任务表异常");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
            }

            // 意见文件
            List<TbPamGeneralOpinionFileDto> opinionFile = value.getOpinionFile();
            if(opinionFile!=null) {
                boolean isOpinionFile=false;
                for (TbPamGeneralOpinionFileDto tbPamGeneralOpinionFileDto : opinionFile) {
                    TbPamGeneralOpinionFile file = new TbPamGeneralOpinionFile();
                    BeanUtils.copyProperties(tbPamGeneralOpinionFileDto,file);
                    file.setHisTaskId(hiTask.getId());
                    if (StringUtils.isNotBlank(tbPamGeneralOpinionFileDto.getDisclosureId()) &&
                            Objects.equals(tbPamGeneralOpinionFileDto.getDisclosureId(), item.getDisclosureId())) {
                        file.setCreateDate(tbPamGeneralOpinionFileDto.getCreateDate()==null?new Date():tbPamGeneralOpinionFileDto.getCreateDate());
                        file.setUpdateDate(tbPamGeneralOpinionFileDto.getUpdateDate()==null?new Date():tbPamGeneralOpinionFileDto.getUpdateDate());
                        file.setCreateBy(tbPamGeneralOpinionFileDto.getCreateBy()==null? UserUtils.getLoginAppUser().getUserId():tbPamGeneralOpinionFileDto.getCreateBy());
                        file.setUpdateBy(tbPamGeneralOpinionFileDto.getUpdateBy()==null?UserUtils.getLoginAppUser().getUserId():tbPamGeneralOpinionFileDto.getUpdateBy());
                        if (tbPamGeneralOpinionFileMapper.insert(file) != 1)
                            try {
                                throw new Exception("添加历史任务表异常");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        isOpinionFile = true;
                    }
                }

                if (!isOpinionFile)
                    for (TbPamGeneralOpinionFileDto tbPamGeneralOpinionFileDto : opinionFile) {
                        TbPamGeneralOpinionFile file = new TbPamGeneralOpinionFile();
                        BeanUtils.copyProperties(tbPamGeneralOpinionFileDto,file);
                        file.setHisTaskId(hiTask.getId());
                        file.setCreateDate(tbPamGeneralOpinionFileDto.getCreateDate()==null?new Date():tbPamGeneralOpinionFileDto.getCreateDate());
                        file.setUpdateDate(tbPamGeneralOpinionFileDto.getUpdateDate()==null?new Date():tbPamGeneralOpinionFileDto.getUpdateDate());
                        file.setCreateBy(tbPamGeneralOpinionFileDto.getCreateBy()==null? UserUtils.getLoginAppUser().getUserId():tbPamGeneralOpinionFileDto.getCreateBy());
                        file.setUpdateBy(tbPamGeneralOpinionFileDto.getUpdateBy()==null?UserUtils.getLoginAppUser().getUserId():tbPamGeneralOpinionFileDto.getUpdateBy());
                        if (tbPamGeneralOpinionFileMapper.insert(file) != 1)
                            try {
                                throw new Exception("添加历史任务表异常");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                    }
            }
        }


    public void test(List<TransferPCTOrPRCDataDto> data){
        data.forEach(value -> {
            List<TbPamOverseasApply> tbPamOverseasApplies = (List<TbPamOverseasApply>) tbPamOverseasApplyService.listByIds(value.getKey().getDisclosureId());
             // 需添加国家
                tbPamOverseasApplies.forEach(item -> {
                    Long nodeId = item.getNodeId();
                    if ((nodeId == 10 || nodeId == 11) &&
                            (value.getTask().getNodeId() != 10
                                    || value.getTask().getNodeId() != 11)){
                        TransferPCTOrPRCDataQuery transferPCTOrPRCDataQuery = new TransferPCTOrPRCDataQuery();
                        BeanUtils.copyProperties(item,transferPCTOrPRCDataQuery);
                        value.getApply().setPatentId(item.getPatentId());
                        String domesticTreeValue = value.getApply().getDomesticTreeValue() == null ? item.getDomesticTreeValue() : value.getApply().getDomesticTreeValue();
                        value.getApply().setDomesticTreeValue(domesticTreeValue);
                        // 获取国家
                        String countryName=null;
                        if (StringUtils.isBlank(value.getCountry())) {
                            if (nodeId == 10 ) {
                                QueryWrapper<TbPamGeneralProcessHiTask> queryWrapper = new QueryWrapper();
                                queryWrapper.eq("data_id",item.getId());
                                queryWrapper.eq("process_type","foreign_apply");
                                queryWrapper.eq("examine_status",0);
                                TbPamGeneralProcessHiTask one = tbPamGeneralProcessHiTaskService.getOne(queryWrapper);
                                countryName = one.getRemarks();
                            }else {
                                TbPamOverseasApplyCountry listByDataId = tbPamOverseasApplyCountryMapper.findListByDataId(item.getId());
                                  countryName = listByDataId.getCountryName();
                            }
                            List<String> list = Arrays.asList(countryName.split(","));
                            List<TbPamOverseasApplyCountryDto> collect = list.stream().map(c -> {
                                TbPamOverseasApplyCountryDto country = new TbPamOverseasApplyCountryDto();
                                country.setCountryName(c);
                                return country;
                            }).collect(Collectors.toList());
                            value.setCountry(collect);
                        }
                        tbPamOverseasApplyService.deleteDataById(item.getId());
                        QueryWrapper<TbPamGeneralProcessTask> queryWrapper2 = new QueryWrapper<>();
                        queryWrapper2.eq("data_id",item.getId());
                        QueryWrapper<TbPamGeneralProcessHiTask> queryWrapper1 = new QueryWrapper<>();
                        queryWrapper1.eq("data_id",item.getId());
                        tbPamGeneralProcessTaskService.remove(queryWrapper2);
                        tbPamGeneralProcessHiTaskService.remove(queryWrapper1);
                        this.saveMigrateData(value,transferPCTOrPRCDataQuery);
                    } else {
                        // 修改审批人和节点
                        TbPamOverseasApply tbPamOverseasApply = new TbPamOverseasApply();
                        BeanUtils.copyProperties(value.getApply(),tbPamOverseasApply);
                        if (StringUtils.isBlank(value.getKey().getNodeId())) {
                            List<String> dataIdList = value.getKey().getDisclosureId();
                            dataIdList.forEach(a -> {
                                tbPamOverseasApply.setId(Long.valueOf(a));
                                try {
                                    this.saveMigrateApply(tbPamOverseasApply);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                QueryWrapper<TbPamGeneralProcessTask> queryWrapper = new QueryWrapper<>();
                                queryWrapper.eq("data_id",a);
                                queryWrapper.eq("process_type","foreign_apply");
                                TbPamGeneralProcessTask task = value.getTask();
                                if (StringUtils.isNotBlank(task.getUserId())) {
                                    task.setRoleId(0l);
                                }
                                if (StringUtils.isNotBlank(task.getRoleId())) {
                                    task.setUserId(null);
                                }
                                tbPamGeneralProcessTaskService.update(task,queryWrapper);
                                QueryWrapper<TbPamGeneralProcessHiTask> queryWrapper1 = new QueryWrapper<>();
                                queryWrapper1.eq("data_id",a);
                                queryWrapper1.eq("process_type","foreign_apply");
                                queryWrapper1.eq("examine_status",0);
                                TbPamGeneralProcessHiTask hiTask = value.getHiTask();
                                if (StringUtils.isNotBlank(hiTask.getUserId())) {
                                    hiTask.setRoleId(0l);
                                }
                                if (StringUtils.isNotBlank(hiTask.getRoleId())) {
                                    hiTask.setUserId(null);
                                }
                                tbPamGeneralProcessHiTaskService.update(hiTask,queryWrapper1);
                            });
                        }
                    }
                });
        });
            }

    @Override
    public IPage<Map<String, Object>> getPatentByArchivesNum(PatentByArchivesNumDto param) {
        Page<Map<String, Object>> page = new Page(param.getPage(),param.getPageSize());
        IPage<Map<String, Object>> patentByArchivesNum = new Page<>();
        switch (param.getPatentType()){
            case 0 :
                  patentByArchivesNum = disclosureMapper.getPatentByArchivesNum(page, param);
                List<Map<String, Object>> records = patentByArchivesNum.getRecords();
                patentServiceImpl.getOperationer(records);
                break;
            case 1 :
                   patentByArchivesNum = tbPamOverseasApplyMapper.getOverseasPatentByArchivesNum(page, param);
                break;
        }
        return patentByArchivesNum;
    }

    public void saveMigrateApply(TbPamOverseasApply data) throws Exception {
                tbPamOverseasApplyService.save(data);
                List<TbPamOverseasApplyFile> applyFileList = data.getApplyFileList();
                if (applyFileList != null && applyFileList.size() > 0) {
                    tbPamOverseasApplyFileMapper.deleteByApplyId(data.getId());
                    for (TbPamOverseasApplyFile tbPamOverseasApplyFile : applyFileList) {
                        tbPamOverseasApplyFile.setCreateDate(tbPamOverseasApplyFile.getCreateDate()==null?new Date():tbPamOverseasApplyFile.getCreateDate());
                        tbPamOverseasApplyFile.setUpdateDate(tbPamOverseasApplyFile.getUpdateDate()==null?new Date():tbPamOverseasApplyFile.getUpdateDate());
                        tbPamOverseasApplyFile.setCreateBy(tbPamOverseasApplyFile.getCreateBy()==null?UserUtils.getLoginAppUser().getUserId():tbPamOverseasApplyFile.getCreateBy());
                        tbPamOverseasApplyFile.setUpdateBy(tbPamOverseasApplyFile.getUpdateBy()==null?UserUtils.getLoginAppUser().getUserId():tbPamOverseasApplyFile.getUpdateBy());
                        tbPamOverseasApplyFile.setOverseasApplyId(data.getId());
                        int insert = tbPamOverseasApplyFileMapper.insert(tbPamOverseasApplyFile);
                        if (insert == 0) {
                            throw new Exception("保存文件出错");
                        }
                    }

                }
            }

    /**
     * @Description:  OA答复模块-通过模块类型搜索
     * @Author: liuqinghua
     * @Date: 2021/8/4
     */
    @Override
    public List<Map<String,String>> getPatentByModelType(PatentByModelTypeDto param) {
        String tableName = "";
        String processType = "";
        switch (param.getModelType()){
            case 1:
                tableName = "tb_pam_patent_oa_correction";
                processType = "patent_bz";
                break;
            case 2:
                tableName = "tb_pam_patent_oa";
                processType = "patent_oa";
                break;
            case 3:
                tableName = "tb_pam_patent_oa_recheck";
                processType = "patent_fs";
                break;
        }
        return disclosureMapper.getPatentByModelType(processType,tableName,param);
    }

    /**
     * @Description: 专利统计
     * @Param:  date 日期
     * @Author: liuqinghua
     * @Date: 2021/9/6
     */
    @Override
    public List<Map<String, Object>> getPatentStatistics(String date) {
        // 参数日期是否是当月
        String now = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM"));
        boolean isNow = false;
        if(now.equals(date))
            isNow = true;
        List<Map<String, Object>> data = new ArrayList<>();
       // 国内在审
        Integer patentStatistics = workflowExecServiceImpl.getPatentStatistics(date,isNow);
        // 海外在审
        Integer foreignApply = tbPamGeneralProcessTaskMapper.getOverseasPatentStatistics(date, "foreign_apply",isNow);
        // 已完成
        Integer patentComplete = disclosureMapper.getPatentComplete(date,isNow);
        Integer overseasComplete = tbPamOverseasApplyMapper.getOverseasComplete(date,isNow);

        Map<String, Object> map = new HashMap<>();
        map.put("name","国内在审");
        map.put("value",patentStatistics == null?0:patentStatistics);
        Map<String, Object> map1 = new HashMap<>();
        map1.put("name","海外相关");
        map1.put("value",foreignApply== null?0:foreignApply);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("name","已完成");
        map2.put("value",(patentComplete== null?0:patentComplete)+(overseasComplete== null?0:overseasComplete));
        Map<String, Object> map3 = new HashMap<>();
        map3.put("name","总提交");
        map3.put("value",(patentComplete== null?0:patentComplete)+(overseasComplete== null?0:overseasComplete)+
                (patentStatistics== null?0:patentStatistics)+(foreignApply== null?0:foreignApply));
        data.add(map);
        data.add(map1);
        data.add(map2);
        data.add(map3);

        return data;

    }


}
